package com.starry.core.web.core.web.filter;

import com.starry.core.common.constants.WebFilterOrderEnum;
import com.starry.core.common.token.context.TokenContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static com.starry.core.common.constants.CommonConstant.Authorization_HEADER;

/**
 * token web 过滤器
 *
 * @author xiaoke
 */
@Order(WebFilterOrderEnum.TENANT_CONTEXT_FILTER)
@Component
public class TokenWebFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        TokenContextHolder.setToken(getToken(request));
        try {
            chain.doFilter(request, response);
        } finally {
            // 清理
            TokenContextHolder.clear();
        }
    }

    public String getToken(HttpServletRequest request) {
        return request.getHeader(Authorization_HEADER);
    }
}
